from django import forms
from django.contrib.auth import get_user_model
from django.template.context_processors import request

from .models import CustomUser
from captcha.fields import CaptchaField,CaptchaTextInput
User = get_user_model()
class LoginForm(forms.Form):
    username =forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    password = forms.CharField(widget=forms.PasswordInput())
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if not CustomUser.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名不存在')
        return username
    def clean_password(self):
        password = self.cleaned_data['password']
        if len(password) < 4:
            raise forms.ValidationError('密码长度需要大于4位')
        user = CustomUser.objects.filter(username=self.cleaned_data.get('username')).first()
        if user.check_password(password):
            return password
        else:
            raise forms.ValidationError('密码错误')

class ChangePasswordForm(forms.Form):
    old_password = forms.CharField(label='输入原密码',widget=forms.PasswordInput(attrs={'class':'form-control'}))
    new_password = forms.CharField(label="输入新密码",widget=forms.PasswordInput(attrs={'class':'form-control'}))
    confirm_password = forms.CharField(label='确认密码',widget=forms.PasswordInput(attrs={'class':'form-control'}))

    def clean_new_password(self):
        password = self.cleaned_data['new_password']
        if len(password) < 3:
            raise forms.ValidationError('密码长度需要大于3')
        return password

    def clean_confirm_password(self):
        password = self.cleaned_data.get('new_password')
        password2 = self.cleaned_data.get('confirm_password')
        if password != password2:
            raise forms.ValidationError('两次输入的密码不一致')
        return password2







class RegistForm(forms.ModelForm):

    password2 = forms.CharField(label="确认密码",widget=forms.PasswordInput(attrs={'class':'form-control'}))
    captcha = CaptchaField(label="验证码",
                           error_messages={"required": "验证码不能为空"},widget=CaptchaTextInput(attrs={'class':'form-control'}))

    class Meta:
        model = CustomUser
        fields = ['email','password']
        widgets = {
            'email': forms.EmailInput(attrs={'class':'form-control'}),
            'password': forms.PasswordInput(attrs={'class':'form-control'}),
        }

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已经存在')
        # 必须返回清洗后的值，否则字段会变成 None
        return email
    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError('用户名已经存在')
        # 必须返回清洗后的值，否则字段会变成 None
        return username


    def clean_password(self):
        password = self.cleaned_data['password']
        if len(password) < 3:
            raise forms.ValidationError('密码长度需要大于3')
        return password

    def clean_password2(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')
        if password and password2 and password != password2:
            raise forms.ValidationError('两次输入的密码不一致')
        return password2

    def save(self, commit=True):
        # 确保密码以哈希形式保存
        user = super().save(commit=False)
        raw_password = self.cleaned_data.get('password')
        if raw_password:
            user.set_password(raw_password)
        if commit:
            user.save()
        return user





